package com.yfuxdeer.youchat.dao.impl;

import com.yfuxdeer.youchat.dao.FriendDao;
import com.yfuxdeer.youchat.pojo.FriendItem;
import com.yfuxdeer.youchat.utils.Store;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class FriendDaoImpl implements FriendDao {

    JdbcTemplate template;

    public FriendDaoImpl() {
        template = new JdbcTemplate(Store.getDataSource());
    }

    @Override
    public List<FriendItem> findAll(String username) {
        List<FriendItem> friendList = template.query("select * from y_friend_item where host_id=?",
                new BeanPropertyRowMapper<FriendItem>(FriendItem.class), new Object[]{username});
        return friendList;
    }

    @Override
    public FriendItem findById(String host_id, String friend_id) {
        List<FriendItem> friendItemList = template.query("select * from y_friend_item where host_id=? and friend_id=?",
                new BeanPropertyRowMapper<>(FriendItem.class), new Object[]{host_id, friend_id});
        if (friendItemList == null || friendItemList.isEmpty()) return null;
        return friendItemList.get(0);
    }

    @Override
    public void add(String host_id, String friend_id) {
        template.update("insert into y_friend values" +
                        "(?,?,(select nickName from y_user where username=?))," +
                        "(?,?,(select nickName from y_user where username=?))",
                new Object[]{host_id, friend_id, friend_id,
                        friend_id, host_id, host_id});
    }

    @Override
    public void updateRemarkByIds(String host_id, String friend_id, String remark) {
        template.update("update y_friend set remark=? where host_id=? and friend_id=?",
                new Object[]{remark, host_id, friend_id});
    }

    @Override
    public void delete(String host_id, String friend_id) {
        template.update("delete from y_friend where " +
                        "(host_id = ? and friend_id = ? )" +
                        " or (host_id = ? and friend_id = ? )",
                new Object[]{host_id, friend_id, friend_id, host_id});
    }
}
